<script setup>
import reserveApi from '@/api/reserveApi';
import {onMounted, reactive, ref, watch} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus'
import doctorSchedulesApi from '@/api/doctorSchedulesApi';
import departmentApi from '@/api/departmentApi';
import patient from "@/api/patient";

const doctorSchedules = defineModel();
const addReserve = ref({doctorSchedulesId: null});
const reserves = ref([]);
// 分页信息
const pageInfo = reactive({
  page: 1,
  limit: 10,
  total: 0
})

// 编辑的操作
const editVisible = ref(false);
const editReserve = ref({});
onMounted(() => {
  // 页面加载完成后直接使用父组件传递的值
  if (doctorSchedules.value && doctorSchedules.value.id) {
    addReserve.value.scheduleId = doctorSchedules.value.id;
    editReserve.value.scheduleId = doctorSchedules.value.id;

    loadReserves();
  }
});
// 可以直接侦听一个 ref
watch(doctorSchedules, async (newDoctorSchedules) => {
  if (newDoctorSchedules && newDoctorSchedules.id) {
    addReserve.value.scheduleId = newDoctorSchedules.id;
    editReserve.value.scheduleId = doctorSchedules.value.id;
    loadReserves();
  }
}, {immediate: true}); // 这里 immediate 可以设为 false，避免第一次空调用



// 页码和页面大小更新
function loadReserves() {
  pageInfo.scheduleId = doctorSchedules.value.id;
  pageInfo.status = "0";
  reserveApi.searchReserves(pageInfo).then(result => {
    reserves.value = result.data.records;
    pageInfo.total = result.data.total;
  });
}

function showEdit(row) {
  editVisible.value = true;
  editReserve.value = JSON.parse(JSON.stringify(row));   // 深拷贝
  editReserve.value.password = "";
  console.log(row);
}

function handleEdit() {
  reserveApi.edit(editReserve.value).then(result => {
    if (result.code == 0) {
      ElMessage({message: '编辑预约成功！', type: 'success'})
      editVisible.value = false;
    } else {
      ElMessage.error(result.msg);
    }
    // 刷新表格数据
    loadReserves();
  });
}

function handleCancel(row, status) {
  ElMessageBox.confirm(
      ['亲，确定要取消当前预约么?',
        '亲，确定要重新预约么?',
        '亲，确定要签到么?',
        '亲，确定要未到么?',][status],
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '不了',
        type: 'warning',
      }
  ).then(() => {
    // 确定
    editReserve.value = JSON.parse(JSON.stringify(row));   // 深拷贝
    editReserve.value.password = "";
    editReserve.value.status = status;
    reserveApi.edit(editReserve.value).then(result => {
      if (result.code == 200) {
        ElMessage({
          message: ['取消预约成功！',
            '重新预约成功！',
            '签到成功！',
            '未到成功！',][status], type: 'success'
        })
        console.log(doctorSchedules.value.id)
      } else {
        ElMessage.error(result.msg);
      }
      // 刷新表格数据
      loadReserves();
    });
  });
}

// 解析类型显示 - 改进版本
function fmtStatus(row, column, cellValue, index) {
  const statusMap = {
    0: '已取消',
    1: '已预订',
    2: '已结束',
    3: '未到'
  };
  return statusMap[row.status] || '未知状态';
}


// 下拉列表
const patients = ref([]);

loadDoctorSchedules();
loadPatient();
const doctorSchedulesList = ref([]);

// 页码和页面大小更新 查询活动
function loadDoctorSchedules() {
  doctorSchedulesApi.search(pageInfo).then(result => {
    // doctorSchedules 本来就是 defineModel()（父组件传下来的对象），不要直接覆盖成数组
    // 这里如果需要活动列表，单独用一个变量存
    doctorSchedulesList.value = result.data.records;
  });
}


function loadPatient() {
  patient.search().then(result => {
    patients.value = result.data;
  });
}

function onSearch() {
  pageInfo.page = 1;
  loadReserves();
}

// 多选
const selectedReserves = ref([])

function handleSelectionChange(val) {
  selectedReserves.value = JSON.parse(JSON.stringify(val));    // 深拷贝
}
const emit = defineEmits(['refreshParent']);

// 批量处理
function handleBatchSign(status) {
  ElMessageBox.confirm(
      ['亲，确定要批量取消预约么?',
        '亲，确定要批量重新预约么?',
        '亲，确定要批量签到么?',
        '亲，确定要批量未到么?',][status],
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '不了',
        type: 'warning',
      }
  ).then(() => {
    // 确定
    for (let reserve of selectedReserves.value) {
      reserve.status = status;
    }
    reserveApi.batchSign(selectedReserves.value).then(result => {
      if (result.code == 200) {
        emit('refreshParent');
        ElMessage({
          message: ['批量取消预约成功！',
            '批量重新预约成功！',
            '批量签到成功！',
            '批量未到成功！',][status], type: 'success'
        })
      } else {
        ElMessage.error(result.msg);
      }
      // 刷新表格数据
      loadReserves();
    });
  });
}

//评分
// 评分相关操作
const ratingVisible = ref(false);
const ratingForm = ref({
  id: '',
  score: 5,  // 默认评分
  comment: ''
});

// 显示评分对话框


// 处理评分提交
function handleRating() {
  reserveApi.rate(ratingForm.value).then(result => {
    if (result.code == 200) {
      ElMessage({message: '评分成功！', type: 'success'});
      ratingVisible.value = false;
      loadReserves(); // 刷新表格数据
    } else {
      ElMessage.error(result.msg);
    }
  });
}

// 在评分相关操作附近添加
// 密码确认相关操作
const passwordConfirmVisible = ref(false);
const passwordForm = ref({
  patientId: '',
  password: ''
});

// 显示密码确认对话框
function showPasswordConfirm(row) {
  passwordForm.value = {
    id: row.patientId,
    password: ''
  };
  passwordConfirmVisible.value = true;
}

// 处理密码确认
function handlePasswordConfirm() {
  // 这里调用后端API验证密码
  patient.verifyPassword(passwordForm.value).then(result => {
    if (result.code == 200) {
      // 密码验证成功，关闭密码确认对话框
      passwordConfirmVisible.value = false;
      // 显示评分对话框
      showRating(currentRatingRow.value);
    } else {
      ElMessage.error(result.msg || '密码错误');
    }
  });
}

// 保存当前要评分的行数据
const currentRatingRow = ref(null);

// 修改 showRating 方法
function showRating(row) {
  // 如果是直接调用（密码验证通过后），则显示评分对话框
  if (currentRatingRow.value === row) {
    ratingForm.value = {
      id: row.id,
      score: row.score || 0,
      comment: row.comment || ''
    };
    ratingVisible.value = true;
    currentRatingRow.value = null;
  } else {
    // 如果是用户点击评分按钮，先进行密码验证
    currentRatingRow.value = row;
    showPasswordConfirm(row);
  }
}

function handleCancelReserve(row){
  ElMessageBox.confirm(
      '亲，确定要取消当前预约么?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '不了',
        type: 'warning',
      }
  ).then(()=>{
    // 确定
    editReserve.value = JSON.parse(JSON.stringify(row));   // 深拷贝
    editReserve.value.password = "";
    editReserve.value.status = 0;
    reserveApi.remove(editReserve.value).then(result=>{
      if (result.code == 200) {
        ElMessage({ message: '取消预约成功！', type: 'success' })
      } else {
        ElMessage.error(result.msg);
      }
      // 刷新表格数据
      loadReserves();
      // 刷新完成后通知父组件
      emit('refreshParent');
    });
  });
}


// 添加发送邮件相关变量和函数
const emailDialogVisible = ref(false);
const emailForm = ref({
  patientId: '',
  content: ''
});

function handleSendEmail() {
  // 立即给用户明确反馈
  ElMessage({
    message: '邮件提交成功！将在后台自动发送。',
    type: 'success',
    duration: 3000
  });
  emailDialogVisible.value = false;

  // 后台异步发送邮件
  reserveApi.sendEmail(emailForm.value).then(result => {
    // 可选：如果需要在发送完成后再次提示
    if (result.code == 200) {
      console.log('邮件已成功发送到服务器');
    } else {
      console.error('邮件发送失败:', result.data || '邮件发送失败');
    }
  }).catch(error => {
    console.error('邮件发送异常:', error);
  });
}

// 显示发送邮件对话框
function sentEmail(row) {
  emailForm.value.patientId = row.patientId;
  emailForm.value.content = '';
  emailDialogVisible.value = true;
}

</script>

<template>
  <div class="content">
    <el-row justify="space-between">
      <el-col :span="12">
        <el-button type="success" @click="handleBatchSign(2)">批量签到</el-button>
        <el-button type="danger" @click="handleBatchSign(3)">批量未到</el-button>
<!--        <el-button type="primary" @click="handleBatchSign(1)">重新预约</el-button>-->
        <el-button type="warning" @click="handleBatchSign(0)">取消预约</el-button>
      </el-col>
      <el-col :span="12">
        <el-form :model="pageInfo" :inline="true">
          <el-form-item label="患者" :label-width="60">
            <el-select
                v-model="pageInfo.patientId"
                filterable
                placeholder="请选择患者"
                style="width: 240px"
                clearable
            >
              <el-option
                  v-for="item in patients"
                  :key="item.id"
                  :label="item.name + '-' + item.phone"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch">
              <el-icon>
                <Search></Search>
              </el-icon>
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-table :data="reserves" :stripe="true" :border="true" style="width: 100%"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40">
      </el-table-column>
      <el-table-column prop="id" label="ID" width="60" fixed/>
      <el-table-column prop="patient.name" label="患者姓名" width="100" fixed/>
      <el-table-column prop="reserveTime" label="预约时间" width="180"/>
      <el-table-column prop="doctorSchedules.name" label="活动名" width="180"/>
      <el-table-column prop="score" label="评分" width="60"/>
      <el-table-column prop="comment" label="评语"/>
      <el-table-column prop="commentTime" label="评价时间" width="180"/>
      <el-table-column prop="status" label="状态" width="80" :formatter="fmtStatus" fixed="right"/>
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="scope">
          <el-button size="small" type="success" v-if="scope.row.status==1 "
                     @click="handleCancel(scope.row, 2)">签到
          </el-button>
          <el-button size="small" type="danger" v-if="scope.row.status==1"
                     @click="handleCancel(scope.row, 3)">未到
          </el-button>
          <el-button size="small" type="primary" v-if="scope.row.status==1"
                     @click="sentEmail(scope.row, 3)">发送邮件
          </el-button>
          <el-button size="small" type="info"
                     v-else-if="scope.row.status==0"
                     disabled>已取消
          </el-button>

          <el-button size="small" type="warning" v-if="scope.row.status==1"
                     @click="handleCancelReserve(scope.row, 0)">取消预订
          </el-button>
          <!-- 评分按钮 -->
          <el-button size="small" type="primary"
                     v-if="scope.row.status==2 && (!scope.row.score || scope.row.score === 0)"
                     @click="showRating(scope.row)">评分
          </el-button>

          <!-- 查看评分按钮 -->
          <el-button size="small" type="info" v-else-if="scope.row.status==2 && scope.row.score > 0"
                     @click="showRating(scope.row)">查看评分
          </el-button>
          <!-- 爽约后无法评分的提示按钮 -->
          <el-button size="small" type="info"
                     v-if="scope.row.status==3"
                     disabled>无法评分
          </el-button>

        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="page" v-model:current-page="pageInfo.page" v-model:page-size="pageInfo.limit"
                   :total="pageInfo.total" :page-sizes="[10, 20, 50, 100]" :background="true"
                   layout="total, sizes, prev, pager, next, jumper" @change="loadReserves"/>
  </div>


  <!-- 编辑的弹窗 -->
  <el-dialog v-model="editVisible" title="编辑预约" width="500">
    <el-form :model="editReserve">
      <el-form-item label="会员" :label-width="60">
        <el-select
            v-model="editReserve.memberId"
            filterable
            placeholder="请选择患者"
            style="width: 240px"
        >
          <el-option
              v-for="item in patients"
              :key="item.id"
              :label="item.name + '-' + item.phone"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="义诊活动" :label-width="60">
        <el-select
            v-model="editReserve.doctorSchedulesId"
            filterable
            placeholder="请选择义诊活动"
            style="width: 240px"
        >
          <el-option
              v-for="item in doctorSchedules"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEdit">
          修改预约
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 评分对话框 -->
  <el-dialog v-model="ratingVisible" title="患者评分" width="500">
    <el-form :model="ratingForm">
      <el-form-item label="评分" :label-width="80">
        <el-rate
            v-model="ratingForm.score"
            :max="5"
            :allow-half="false"
            show-score
            score-template="{value}分">
        </el-rate>
      </el-form-item>
      <el-form-item label="评语" :label-width="80">
        <el-input
            v-model="ratingForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入评语">
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="ratingVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRating">提交评分</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 密码确认对话框 -->
  <el-dialog v-model="passwordConfirmVisible" title="身份验证" width="500">
    <el-form :model="passwordForm">
      <el-form-item label="请输入患者密码" :label-width="120">
        <el-input
            v-model="passwordForm.password"
            type="password"
            show-password
            placeholder="请输入患者密码">
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="passwordConfirmVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePasswordConfirm">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 发送邮件对话框 -->
  <el-dialog v-model="emailDialogVisible" title="发送邮件" width="500">
    <el-form :model="emailForm">
      <el-form-item label="患者ID" :label-width="80">
        <el-input v-model="emailForm.patientId" disabled></el-input>
      </el-form-item>
      <el-form-item label="邮件内容" :label-width="80">
        <el-input
            v-model="emailForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入邮件内容">
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="emailDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSendEmail">发送邮件</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<style>

</style>